# -*- coding: utf-8 -*-
import threading
import time
import traceback

from PyQt5.QtWidgets import QMainWindow
import qtawesome as qta

from global_data.glabal_data import GlobalData
from mq.zmq.zmq_tools import Client
from utils.icloudp_log import IcloudpLog
from utils.time_utils import TimeUtils
from windows.zmq_sub import Ui_win_zmq_sub


class ZmqSubForm(object):
    def __init__(self, id, parent):
        self.log = IcloudpLog.get_logger_zmq()
        self.id = id
        self.parent = parent
        self.flag = 1
        self.receiver_thread = None
        self.client = None
        self.ui = Ui_win_zmq_sub()
        self.win = QMainWindow()
        self.win.setWindowIcon(qta.icon(GlobalData.SYS_ICON))
        self.init()
        self.bind_events()

    def init(self):
        self.ui.setupUi(self.win)
        self.ui.txt_ip.setText(GlobalData.ZMQ_XPUB_IP)
        self.ui.txt_port.setText(GlobalData.ZMQ_XPUB_PORT)
        self.ui.txt_topic.setText("alarm")

    def bind_events(self):
        self.ui.btn_start_sub.clicked.connect(self.start)
        self.ui.btn_stop_sub.clicked.connect(self.stop)

    def create_client(self):
        self.client = Client(host=self.ui.txt_ip.text(), port=self.ui.txt_port.text(), topic=self.ui.txt_topic.text(),
                             handle=self.monitor_zmq)

    def start(self):
        if self.client:
            self.ui.tb_content.append(f"订阅已启动，请不要重复启动。。。。。")
        else:
            self.ui.tb_content.append(f"启动订阅线程。。。。。")
            self.create_client()
            try:
                self.receiver_thread = threading.Thread(target=self.client.run)
                self.receiver_thread.setDaemon(True)  # 守护线程  主线程退出后，自动退出
                self.receiver_thread.start()
            except Exception as e:
                self.log.error('订阅代理服务启动失败： {}'.format(str(traceback.format_exc())))

    def stop(self):
        try:
            # if self.receiver_thread:
            #     self.receiver_thread.stop()
            #     self.ui.tb_content.append(f"停止订阅线程。。。。。")
            if self.client:
                self.client.close()
                time.sleep(1)
                self.client = None
                self.ui.tb_content.append(f"停止订阅服务。。。。。")
            else:
                self.ui.tb_content.append(f"订阅服务不存在。。。。。")
        except Exception as e:
            self.ui.tb_content.append(f"停止服务失败: {e}")

    def monitor_zmq(self, topic, content):
        # while True:
        #     try:
        #         if self.flag == 0:
        #             data = self.client.recv_multi()
        #             content = data.data
        #         else:
        #             content = self.client.recv_multi_str()
        #     except Exception as e:
        #         content = f"解析数据错误: {e}"
        self.ui.tb_content.append(f"接收内容: time={TimeUtils.get_current_time()}, topic={topic}content={content}")


if __name__ == '__main__':
    print("Python")
